package com.flow.asyncflow.core.utils.log.businesslog;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.flow.asyncflow.core.entity.core.AsyncFlowBaseContext;
import com.flow.asyncflow.core.entity.core.AsyncFlowRequest;
import com.flow.asyncflow.core.entity.log.businesslog.AsyncFlowBusinessLogEntity;
import com.flow.asyncflow.core.entity.log.businesslog.SaveBusinessLogEntity;
import com.flow.asyncflow.core.utils.http.AsyncFlowHttpClientUtil;
import com.flow.asyncflow.core.utils.msg.AsyncFlowSendMsg;
import org.apache.commons.lang.StringUtils;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.stream.Collectors;

/**
 * 业务日志
 */
public class AsyncFlowBusinessLog {
    /**
     * 添加业务日志
     * @param orderFlowData 上下文
     * @param logInfo       日志内容
     * @param mustRecord    是否必须记录
     */
    public static void addBusinessLog(AsyncFlowBaseContext orderFlowData, String logInfo, boolean mustRecord) {
        AsyncFlowBusinessLogEntity asyncBusinessLogEntity = new AsyncFlowBusinessLogEntity();
        asyncBusinessLogEntity.setLogInfo(logInfo);
        asyncBusinessLogEntity.setLocalDateTime(LocalDateTime.now());
        asyncBusinessLogEntity.setMustRecord(mustRecord);
        orderFlowData.getAsyncBusinessLogEntityList().add(asyncBusinessLogEntity);
    }


    /**
     * 添加业务日志
     * @param asyncFlowRequest 请求
     * @param asyncFlowData 上下文
     * @param msg 日志
     * @param allNodeIsSuccess  节点状态
     * @param <TAsyncContext> 具体上下文
     */
    public static void saveBusinessLog(AsyncFlowRequest asyncFlowRequest, AsyncFlowBaseContext asyncFlowData, String msg, boolean allNodeIsSuccess) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            String reason;
            if (!allNodeIsSuccess) {
                reason = "失败原因：" + msg;
                AsyncFlowBusinessLog.addBusinessLog(asyncFlowData, reason, true);
            }
            if (asyncFlowData.getAsyncBusinessLogEntityList().isEmpty()) {
                return;
            }

            if (StringUtils.isBlank(asyncFlowRequest.getBusinessSerialId())) {
                return;
            }
            //基础日志内容
            String logInfo = "【" + asyncFlowRequest.getSourceDes() + "】触发【" + asyncFlowRequest.getReqTypeEnumMsg()+ "】【" + (allNodeIsSuccess ? "成功" : "失败") + "】";
            for (AsyncFlowBusinessLogEntity orderLogEntity : asyncFlowData.getAsyncBusinessLogEntityList().stream().sorted(Comparator.comparing(AsyncFlowBusinessLogEntity::getLocalDateTime)).collect(Collectors.toList())) {
                //在失败的情况下，仅仅记录必须要记录的日志（非必须的不记录-跳过）
                if (!allNodeIsSuccess && !orderLogEntity.isMustRecord()) {
                    continue;
                }
                stringBuilder.append(orderLogEntity.getLogInfo()).append("<Br/>");
            }
            String log = stringBuilder.toString() + logInfo;
            SaveBusinessLogEntity saveBusinessLogEntity = new SaveBusinessLogEntity();
            saveBusinessLogEntity.setBusinessSerialId(asyncFlowRequest.getBusinessSerialId());
            if (StringUtils.isBlank(asyncFlowRequest.getOperateName())) {
                asyncFlowRequest.setOperateName("0");
            }
            if (StringUtils.isBlank(asyncFlowRequest.getOperateNo())) {
                asyncFlowRequest.setOperateNo("0");
            }
            saveBusinessLogEntity.setOperateName(asyncFlowRequest.getOperateName());
            saveBusinessLogEntity.setOperateNo(asyncFlowRequest.getOperateNo());
            saveBusinessLogEntity.setLogInfo(log);
            saveBusinessLogEntity.setLogTime(LocalDateTimeUtil.format(asyncFlowRequest.getRequesterTime(), DatePattern.NORM_DATETIME_PATTERN));
            String result = AsyncFlowHttpClientUtil.post(asyncFlowData.getAsyncFlowInfo().getBusinessLogUrl(), saveBusinessLogEntity);
            JSONObject jsonObject = JSONObject.parseObject(result);
            int code = jsonObject.getShort("Code");
            if (code != 200) {
                String errorMsg = jsonObject.getString("Msg");
                AsyncFlowSendMsg.sendAlarmMsg(asyncFlowRequest, errorMsg, "保存业务日志", asyncFlowData.getAsyncFlowInfo());
            }
        } catch (Exception e) {
            String s = AsyncFlowSendMsg.buildErrorMsg(asyncFlowRequest, e, "保存业务日志", asyncFlowData.getAsyncFlowInfo());
            AsyncFlowSendMsg.sendQYWXMsg(asyncFlowData.getAsyncFlowInfo().getFlowMaintainName(), s, asyncFlowData.getAsyncFlowInfo().getNodeArmUrl());
        }


    }
}
